package com.xinqi.common.base.dto.utils;

import com.xinqi.common.base.dto.CommonFileDTO;
import com.xinqi.common.base.utils.json.JSON;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.Collections;
import java.util.List;
import java.util.Objects;

/**
 * @author linkai
 * @date 2023/3/24
 */
public interface CommonFileUtils {
    static Long fileSize(String json) {
        return fileSize(toFileObj(json));
    }

    static Long fileSize(List<CommonFileDTO> files) {
        if (CollectionUtils.isEmpty(files)) {
            return 0L;
        }
        return files.stream()
            .map(v -> v.getSize() != null ? v.getSize() : 0L)
            .reduce(Long::sum).orElse(0L);
    }

    static List<CommonFileDTO> toFileObj(String json) {
        if (StringUtils.isBlank(json)) {
            return Collections.emptyList();
        }
        return JSON.parseList(json, CommonFileDTO.class);
    }

    static int fileLevel(String filePath) {
        int count = 0;
        if (StringUtils.isBlank(filePath)) {
            return count;
        }
        for (char c : filePath.toCharArray()) {
            if (Objects.equals(c, '/')) {
                count++;
            }
        }
        return count;
    }

    static String filePath(String fileName) {
        return "/" + fileName;
    }

    static String filePath(String fileName, String parentPath) {
        return StringUtils.isEmpty(parentPath) ? "/" + fileName : parentPath + "/" + fileName;
    }
}
